import React,{useState} from 'react';
import { useNavigate } from 'react-router-dom';
import InputElement from '../components/InputElement';
import { reg } from '../services/user';
export default () => {
    let [username,setUsername] = useState({
        value:"",
        info:""
    });
    let [pwd,setPwd] = useState({
        value:"",
        info:""
    });
    let [confirm,setConfirm] = useState({
        info:""
    });
    let navigate = useNavigate();

    const validateUsername = (e) => {
        if(/^\w{6,20}$/.test(e.target.value)){
            setUsername({
                    value:e.target.value,
                    info:"√"
                });
        }else{
            setUsername({
                value:e.target.value,
                info:"X"
            });
        }
    }
   const validatePwd = (e) => {
        if(/^.{6,20}$/.test(e.target.value)){
            setPwd({
                value:e.target.value,
                info:"√"
            });
        }else{
            setPwd({
                value:e.target.value,
                info:"X"
            });
        }
    }
    const validateConfirm = (e) => {
        if(e.target.value == pwd.value){
            setConfirm({
                info:"√"
            });
        }else{
            setConfirm({
                info:"两次密码不一致"
            });
        }
    }
    const handleSubmit = async ()=>{
        if(username.info == "√"
            && pwd.info == "√"
            && confirm.info == "√"){
                // console.log("注册成功",username.value,pwd.value);
                let data = await reg({username:username.value,pwd:pwd.value});
                console.log("data",data);
                navigate("/login");
        }else{
            console.log("验证失败");
        }
        
    }
    return <div>
                    <h1>注册</h1>
                    <InputElement handleValidate={validateUsername} 
                    info={username.info}
                    value={username.value}
                    onInput={(e) => setUsername({value:e.target.value})}
                    >用户名：</InputElement>

                    <InputElement type="password"
                    info={pwd.info}
                    handleValidate={validatePwd} 
                    onInput={(e) => setPwd({value:e.target.value})}
                    >密码：</InputElement>

                    <InputElement
                    info={confirm.info}
                    handleValidate={validateConfirm} 
                    type="password">确认密码：</InputElement>
                    <input type="button" value="提交" onClick={handleSubmit}/>
                </div>
}